<template>
  <div
    class="page-box h100 vertical-center dfdsfdsrter"
    :class="xz ? 'act' : ''"
    :data-seer="seer"
    :data-TbleName="TbleName"
  >
    <div class="display-flex h100">
      <div class="msg-left">
        <template v-for="(sd, idx) in userList" :key="idx">
          <div
            class="display-flex pd pt10 pm10 gfdgtlist sz"
            :class="idx == dxPeer.state.pitchOnNumber ? 'act' : ''"
            @click="getliaot(sd, idx)"
          >
            <img class="user-icon-left cove" :src="sd.headPortrait" />
            <div class="flex-1 pl10">
              <p class="fz16 display-flex">
                <span
                  class="flex-1 wweertw nowrap"
                  :data-currentTime="currentTime"
                  >{{ sd.userNickname }}</span
                >
                <span class="fz12 z9">{{
                  handleDateVue(sd.turnoverTime)
                }}</span>
              </p>
              <p class="fz12 z9 dianer" v-if="sd.msgBody">
                <span v-if="ISimgvue(sd.msgBody) == '[图片]'"> [图片] </span>
                <span v-else>
                  {{ entitiestoUtf16s(sd.msgBody) }}
                </span>
              </p>
            </div>
          </div>
        </template>
      </div>
      <div class="msg-box display-flex czbj">
        <div class="msg-title">
          <i class="iconfont dx-zuojiantou back-icon pr" @click="backFun"> </i>
          {{ userNameTitle || "---" }}
        </div>
        <div class="dsfdsrtte flex-1" id="new_message">
          <div v-if="destName">
            <div v-for="(item, idx) in dataList" :key="idx">
              <div class="cen">
                <span
                  v-if="
                    idx > 0 &&
                    gerq(item.turnoverTime, dataList[idx - 1].turnoverTime)
                  "
                >
                  {{ gerq(item.turnoverTime, dataList[idx - 1].turnoverTime) }}
                </span>
                <span v-if="idx == 0"> {{ gerq(item.turnoverTime, 0) }} </span>
              </div>
              <div
                class="dsfrrtw"
                :class="item.fromName == userName ? 'tr' : ''"
              >
                <img :src="item.headPortrait" class="user-icon cz cove" />
                <span>
                  <n-image
                    :src="item.msgBody"
                    v-if="ISimgvue(item.msgBody) == '[图片]'"
                    class="img-text"
                  />
                  <span v-else class="msg-text">
                    {{ entitiestoUtf16s(item.msgBody) }}
                  </span>
                </span>
              </div>
            </div>
          </div>
        </div>
        <div class="sen-box">
          <div class="pl10">
            <n-popover trigger="hover">
              <template #trigger>
                <i class="iconfont dx-xiaolian z9 fz20 sz"></i>
              </template>
              <expression @getText="getText"></expression>
            </n-popover>
            <i
              class="iconfont z9 fz20 dx-tupian1 ml20 sz"
              @click="photoShowModal = true"
            ></i>
            <!-- <i class="iconfont z9 fz20 dx-dianhua ml20 sz"></i> -->
            <i
              class="iconfont z9 fz20 dx-shipin ml20 sz"
              v-if="userNameTitle"
              @click="videoCallVue"
            ></i>
          </div>

          <textarea
            id="textarea"
            class="sen-textarea"
            v-model="tbbse"
            placeholder="请输入内容..."
          />
          <p class="tr pr10">
            <n-button type="info" @click="faxx(false)" v-if="userNameTitle">
              发送
            </n-button>
          </p>
        </div>
      </div>

      <div class="vertical-center">
        <peerJs></peerJs>
        <!-- <TheVideoFrame ref="TheVideoFrameRef"></TheVideoFrame> -->
      </div>
    </div>

    <n-modal
      v-model:show="photoShowModal"
      preset="card"
      class="Stock-diagnosis"
    >
      <template #header>
        <div>图片库</div>
      </template>
      <div>
        <photoGallery @getImg="getImg"></photoGallery>
      </div>
      <template #action>
        <div class="tr">
          <n-button @click="photoShowModal = false"> 取消 </n-button>
          <n-button class="ml10" type="info" @click="pupImgfs"> 确定 </n-button>
        </div>
      </template>
    </n-modal>
    <div class="kknkxeertw vertical-center" v-if="!dxPeer.state.ismsgopen">
      <div class="kmmseert cf">
        <n-spin size="small" stroke="#fff" />
        <span>正在与对方建立连接...</span>
      </div>
    </div>
  </div>
</template>
 <script lang='ts' setup>
import { ref, computed, watch, onUpdated } from "vue";
import { NPopover, NImage } from "naive-ui";
import photoGallery from "../../components/util/photoGallery";
import peerJs from "../../components/peerJs/index";
import {
  dxget,
  qurl,
  handleDate,
  transferTimeYMDHm,
  transferHm,
  transferTimeYMD,
  utf16toEntities,
  entitiestoUtf16,
  ISimg,
} from "../../util/index";
import { onBeforeRouteUpdate } from "vue-router";
import store from "../../store";
import dxPeer from "../../store/dxPeer";
import expression from "../../components/websocket/expression";
let userName = localStorage.userNmae;
let tbbse = ref("");
let dataList: any = ref();
let userList = ref();
let userNameTitle = ref();
let userNamedf = ref();
store.state.msgList = [];
let hbjhhe = 1;
let idxs = ref(-1);
let photoShowModal = ref(false);
let imgVal = ref();
let xz = ref(false);
// dataList = store.state.msgList;
let destName = ref("");
let usBom = ref(true);
let qyyr = qurl();
let issc = true;
let msgFst = ref({
  turnoverTime: new Date().getTime(),
  fromName: localStorage.userNmae,
  msgBody: "",
  headPortrait: localStorage.headPortrait,
});

// 路由值有变化触发 一般在收到消息点击消息=框才会执行
onBeforeRouteUpdate((to) => {
  let query = to.query;
  query.userNmae = query.fromName;
  getliaot(query, -1);
});

// 发送按钮触发
const faxx = (ty?) => {
  if (!tbbse.value.trim() && !ty) {
    window.$message.error("不能发送空白文本");
    return;
  }
  let msgVal = tbbse.value;
  let MSgjs = utf16toEntities(msgVal);
  if (ty) {
    msgVal = imgVal.value;
    MSgjs = imgVal.value;
  }
  window.socket.emit("faSong", {
    destName: destName.value,
    fromName: localStorage.userNmae,
    msgBody: MSgjs,
  });
  msgFst.value.msgBody = msgVal;
  dataList.value.push({
    turnoverTime: new Date().getTime(),
    fromName: localStorage.userNmae,
    msgBody: msgVal,
    headPortrait: localStorage.headPortrait,
  });
  dxPeer.commit("setIdx", 0);
  getUser();
  imgVal.value = "";
  tbbse.value = "";
  var container = document.querySelector("#new_message");
  container.scrollTop = container.scrollHeight + 50;
};
const getImg = (img) => {
  imgVal.value = img;
};
// 图片弹出确定按钮触发
const pupImgfs = () => {
  photoShowModal.value = false;
  faxx(true);
};
// 获取消息记录
const getmsg = async () => {
  let { data }: any = await dxget("websocket/getMsg", {
    destName: destName.value,
  });
  store.state.msgList = data;
  dataList.value = data;
};
// 获取用户列表
const getUser = async () => {
  let { data }: any = await dxget("websocket/GetTheLatestNews");
  userList.value = data;
  if (issc && qyyr.id) {
    userList.value.map((a, b) => {
      if (a.userNmae == qyyr.fromName) {
        dxPeer.commit("setIdx", b);
      }
    });
  }
  issc = false;
};

// 点击左侧用户获取当前用户聊天信息
const getliaot = (data, idx) => {
  destName.value = data.userNmae;
  store.state.msgFrom = data.userNmae;
  userNameTitle.value = data.userNickname;
  userNamedf.value = data.userNmae;
  usBom.value = true;
  hbjhhe = 1;
  if (idx > -1 && store.state.windowSize < 750) {
    xz.value = true;
    store.state.isheader = false;
    window.history.pushState(null, "");
  }
  data.fromName = data.userNmae;
  dxPeer.commit("setIdx", idx);
  dxPeer.commit("setMsg", data);
  getmsg();
};
// 左侧用户列表时间转换
const handleDateVue = (dateTime) => {
  return handleDate(dateTime);
};

// 接手到消息触发
const seer = computed(() => {
  getUser();
  return store.state.ReceiveMessage;
});

const TbleName = computed((data) => {
  try {
    userList.value.map((a, b) => {
      if (a.userNmae == dxPeer.state.TbleName) {
        dxPeer.commit("setIdx", b);
        dxPeer.commit("setMsg", a);
      }
    });
  } catch (E) {}
  return dxPeer.state.TbleName;
});

// 3秒全局定时器
let dqse = 0;
const currentTime = computed(() => {
  usBom.value = false;
  return store.state.currentTime;
});
// 路由后面有参数 一般在收到消息点击消息=框才会执行
if (qyyr) {
  qyyr.userNmae = qyyr.fromName;
  getliaot(qyyr, -1);
}
// 聊天记录的时间
const gerq = (a, b?) => {
  let jkjne = a - b;
  let str = "";
  let nData = new Date().getTime();
  let nowDate = nData - a;
  if (!b) {
    return (str = transferTimeYMDHm(a));
  }
  // 今天
  if (transferTimeYMD(a) == transferTimeYMD(nData)) {
    str = transferHm(a);
  } else if (nowDate) {
    str = transferTimeYMDHm(a);
  }

  // 合并近五分钟的消息
  if (jkjne < 1000 * 60 * 5) {
    str = "";
  }

  return str;
};

// 页面数据更新聊天框滚动到底部
onUpdated(() => {
  if (!usBom.value) {
    return;
  }
  var container = document.querySelector("#new_message");
  container.scrollTop = container.scrollHeight + 50;
  let position = document.getElementsByTagName("textarea")[0];
  if (store.state.windowSize > 760) {
    position.focus();
  }
});
// 表情选中完了回调方法
const getText = (data) => {
  let evl = data.evl;
  tbbse.value = data.text;
  setTimeout(() => {
    evl.focus();
    evl.setSelectionRange(data.pos, data.pos);
  }, 100);
};
// 解码表情
const entitiestoUtf16s = (text) => {
  return entitiestoUtf16(text);
};
const ISimgvue = (str) => {
  return ISimg(str);
};
const backFun = () => {
  history.go(-1);
};
window.addEventListener(
  "popstate",
  function (e) {
    store.state.isheader = true;
    xz.value = false;
  },
  false
);
const videoCallVue = () => {
  if (userNamedf.value == "kf") {
    window.$message.error("客服小姐姐没有视频头！");
    return;
  }
  if (dxPeer.state.TheActive != 0) {
    window.$message.error("您正在视频聊天中...");
    return;
  }
  dxPeer.commit("dialCall", userNamedf.value);
};
</script>

 <style scoped>
.bgred {
  background: red;
}
.dsfdsrtte {
  /* height: 600px; */
  border-bottom: 1px solid #e0e0e0;
  overflow: auto;
  padding: 0 10px 50px;
}
.user-icon,
.user-icon-left {
  width: 38px;
  height: 38px;
  border-radius: 8px;
  object-fit: cover;
}
.user-icon-left {
  width: 44px;
  height: 44px;
}
.msg-text {
  background: #fff;
  box-shadow: 0 0 6px rgba(0, 0, 0, 0.2);
  margin-left: 10px;
  padding: 7px 10px;
  border-radius: 8px;
  max-width: 700px;
}
.dsfrrtw.tr .msg-text {
  background: #9eea6a;
}
.dsfrrtw {
  margin-top: 12px;
  margin-bottom: 12px;
  display: flex;
  width: 100%;
}
.sen-box {
  height: 260px;
}
.dsfrrtw.tr {
  flex-direction: row-reverse;
}
.dsfrrtw.tr span {
  margin-left: 0;
  margin-right: 10px;
}
.msg-left {
  width: 250px;
  height: 100%;
  background: #e4e5e7;
  overflow: auto;
}
.msg-box {
  border: 1px solid #e0e0e0;
  width: 800px;
}
.msg-title {
  line-height: 70px;
  padding: 0 20px;
  font-size: 20px;
  border-bottom: 1px solid #e0e0e0;
}
.sen-textarea {
  width: 100%;
  height: 150px;
  border: 0;
  padding: 10px;
  font-size: 16px;
  resize: none;
}
.gfdgtlist:hover,
.gfdgtlist.act {
  background: #dfdcdb;
}
.wweertw {
  max-width: 120px;
  overflow: hidden;
  margin-right: 15px;
}
.img-text {
  max-width: 200px;
}
.kmmseert {
  background: rgba(0, 0, 0, 0.6);
  border-radius: 4px;
  padding: 5px 10px;
}
.kmmseert span {
  margin-left: 10px;
  position: relative;
  bottom: 5px;
}
.kknkxeertw {
  position: fixed;
  left: 0;
  top: 0;
  width: 100%;
  height: 100%;
  z-index: 9999;
}
</style>